package cn.cmkj.auction.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.AuctionPriceListAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Auction;
import cn.cmkj.auction.data.http.AuctionPrice;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.ItemClickSupport;
import cn.cmkj.auction.widget.PriceUpDialog;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2018-05-08.
 */
@ContentView(R.layout.activity_auction_price_list)
public class AuctionPriceListActivity extends BaseActivity implements MySwipeMenuRecyclerView.OnLoadListener, View.OnClickListener {

    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeRecyclerView;
    @ViewInject(R.id.btn_price)
    private Button priceButton;

    private List<AuctionPrice> mData;
    private AuctionPriceListAdapter auctionPriceListAdapter;
    private boolean requesting = false;
    private int page = 1;
    private Auction auction;
    private PriceUpDialog priceDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        Intent intent = getIntent();
        if(intent == null) {
            finish();
            return;
        }
        auction = (Auction)intent.getSerializableExtra("auction");
        if(auction == null) {
            finish();
            return;
        }
        if(auction.getStatus() != 2 && !auction.isFrontMoney()) {
            finish();
            return;
        }
        if(auction.getStatus() == 2) {
            priceButton.setEnabled(false);
            priceButton.setText("出价结束");
        }
        mData = new ArrayList<>();
        auctionPriceListAdapter = new AuctionPriceListAdapter(this, mData);
        swipeRecyclerView.getRecyclerView().setLayoutManager(new GridLayoutManager(this, 1));
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); // 开启滑动删除。
        swipeRecyclerView.setAdapter(auctionPriceListAdapter);
        ItemClickSupport.addTo(swipeRecyclerView.getRecyclerView()).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {

            }
        });
        swipeRecyclerView.setOnLoadListener(this);
        swipeRecyclerView.setRefreshing(true);
        priceButton.setOnClickListener(this);
        titleBack.setOnClickListener(this);
        titleText.setText("出价实况");
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            page = 1;
            mData.clear();
            auctionPriceListAdapter.notifyDataSetChanged();
            fetchData();
        }
    }

    @Override
    public void onLoadMore() {
        if(!requesting) {
            page = page +1;
            LogUtil.e("--onLoadMore:page=" + page);
            fetchData();
        }
    }

    public void fetchData() {
        requesting = true;
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            RequestParams params = new RequestParams(Urls.api);
            params.addParameter("method", Urls.auctionPriceList);
            params.addParameter("auction_id", auction.getId());
            params.addParameter("page_no", page);
            params.addParameter("page_size", Urls.pageSize);
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    requesting = false;
                    swipeRecyclerView.complete();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(s);
                        JSONObject json = jsonObject.optJSONObject("data");
                        JSONArray jsonArray = json.optJSONArray("data");
                        List<AuctionPrice> temp = AuctionPrice.parseJsonArray(jsonArray);
                        mData.addAll(temp);
                        auctionPriceListAdapter.notifyDataSetChanged();
                        if (Urls.pageSize > temp.size()) {
                            swipeRecyclerView.setLoadMoreEnable(false);
                        } else {
                            swipeRecyclerView.setLoadMoreEnable(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    requesting = false;
                    swipeRecyclerView.complete();
                    if (ex != null) ex.printStackTrace();
                    LogUtil.e("---onError-----" + "onError");
                    Toast.makeText(AuctionPriceListActivity.this, TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void cancel(CancelledException cex) {
                    requesting = false;
                    swipeRecyclerView.complete();
                    LogUtil.e("---onCancelled-----" + "onCancelled");
                }
            });
        }
    }

    private void popGivePriceDialog() {
        if(priceDialog == null) {
            priceDialog = new PriceUpDialog(this).builder().setTitle("提示")
                    .setMsg("当前竞拍价格为￥" + auction.getNowPrice() + ",加价幅度不小于￥" + auction.getPriceMarkup() + ",请输入竞拍价")
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            priceDialog.dismiss();
                        }
                    }).setCancelable(true).setCanceledOnTouchOutside(false);
            priceDialog.show();
        }else {
            priceDialog.show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.btn_price:
                if(auction.isFrontMoney()) {
                    if(auction.getStatus() == 1 || auction.getStatus() == 2) {//出价
                        popGivePriceDialog();
                    }
                }
                break;
        }
    }
}
